package com.mega.center.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.mega.center.auth.enums.msg.AuthMsgEnum;
import com.mega.center.system.service.IUserService;
import com.mega.common.core.constant.UserConstants;
import com.mega.common.core.enums.CommonStatus;
import com.mega.common.core.exception.BusinessException;
import com.mega.common.core.utils.StringUtils;
import com.mega.common.security.utils.SecurityUtils;
import com.mega.system.api.vo.LoginUser;
import com.mega.system.api.vo.UserAuthInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 登录校验方法
 *
 * @author mega
 */
@Component
public class LoginService {

    @Autowired
    private IUserService userService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException(AuthMsgEnum.USER_PASSWORD_NOT_NULL);
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new BusinessException(AuthMsgEnum.USER_PASSWORD_LENGTH_NOT_VALID);
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new BusinessException(AuthMsgEnum.USER_USERNAME_LENGTH_NOT_VALID);
        }
        // 查询用户信息
        LoginUser loginUser = this.getUserInfo(username);
        //用户被封禁
        if (CommonStatus.DISABLED.getCode().equals(loginUser.getUser().getStatus())) {
            throw new BusinessException(AuthMsgEnum.USER_BLOCKED, username);
        }
        //用户密码错误
        if (!SecurityUtils.matchesPassword(password, loginUser.getUser().getPassword())) {
            throw new BusinessException(AuthMsgEnum.USER_PASSWORD_ERROR);
        }
        //登录成功
        return loginUser;
    }

    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    public LoginUser getUserInfo(String username) {
        UserAuthInfo userAuthInfo = userService.getUserAuthInfoForLogin(username);
        LoginUser loginUser = new LoginUser();
        BeanUtil.copyProperties(userAuthInfo, loginUser);
        loginUser.setUserId(userAuthInfo.getUser().getId());
        loginUser.setUserName(userAuthInfo.getUser().getUserName());
        //将模块中的所有权限汇总
        Set<String> allPermissions = new HashSet<>();
        if (CollectionUtil.isNotEmpty(loginUser.getPermissions())) {
            loginUser.getPermissions().forEach((k, v) -> {
                allPermissions.addAll(v);
            });
        }
        loginUser.setAllPermissions(allPermissions);
        return loginUser;
    }
}